package com.eric.flowabledemo.strategy;

import com.eric.flowabledemo.constant.ResponseCodeEnum;
import com.eric.flowabledemo.constant.RmaStatusEnum;
import com.eric.flowabledemo.exception.ProcessExceptionCast;
import com.eric.flowabledemo.factory.RmaProcessStrategyFactory;
import com.eric.flowabledemo.model.request.ProcessRequestData;
import com.eric.flowabledemo.model.response.ResponseResult;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 这个执行器，会牵扯到具体流程
 * 因此，选用的框架只要适配这个执行器即可
 */
@Component
public class RmaProcessExecutor {
    private static final Logger LOGGER = LoggerFactory.getLogger(RmaProcessExecutor.class);

    @Autowired
    private TaskService taskService;

    /**
     * 下一步
     * @param requestData
     * @return
     */
    @Transactional
    public ResponseResult complete(ProcessRequestData requestData){
        //取当前状态，以repair为例子:taskService.createTaskQuery().taskAssignee("REPAIR").processInstanceBusinessKey(requestData.getBusinessKey()).singleResult();
        Task task = taskService.createTaskQuery().processInstanceBusinessKey(requestData.getBusinessKey()).singleResult();
        if(task == null){
            ProcessExceptionCast.cast(ResponseCodeEnum.SERVER_ERROR);
        }
        String status = task.getName();
        //取策略
        AbstractRmaProcessStrategy strategy = RmaProcessStrategyFactory.getStrategy(RmaStatusEnum.valueOf(status));
        //校验
        ResponseResult validateResp = strategy.validate(requestData);
        if(!validateResp.isSuccess()){
            return validateResp;
        }
        //执行前
        strategy.beforeComplete(requestData);
        //执行中
        LOGGER.info("处理通用的业务逻辑...");
        taskService.complete(task.getId(), requestData.getVariableParams());
        //执行后
        strategy.afterComplete(requestData);

        //返回执行成功
        return new ResponseResult(ResponseCodeEnum.COMPLETE, status);
    }
}
